include Java

require 'rubygems'
require 'rubeus'
require 'mouse_handler'
require 'key_handler'
require 'net/http'
require 'rexml/document'
require 'bidirectional_generator'

class Presen
	include Rubeus::Awt
	include Rubeus::Swing
  
  def initialize
    self.load
  end
  
	def show
		@frame = JFrame.new do |frame|
			frame.visible = true
			frame.set_background Color.black
			@message = JLabel.new 'RubeusPresen on Rails'
			@message.set_foreground Color.white
			@message.set_horizontal_alignment 0
			@message.set_vertical_alignment 0
			@mouse_handler = MouseHandler.new(self)
      @message.add_mouse_listener @mouse_handler
		end
    @frame.add_key_listener KeyHandler.new(self)
	  large
	end
	
	def load
    Net::HTTP.start('localhost', 3000) do |http|
      @result = http.get('/messages.xml')
    end
  	doc = REXML::Document.new @result.body

    load_message = []
    doc.elements.each('/messages/message') do |node|
      load_message << {
        :message => node.elements['message'].text, 
        :extention => node.elements['extention'].text
      }
    end
    @slide_iterator = BidirectionalGenerator.new(load_message)
  end
  
  def small
	  @small_font ||= Font.new "Default", 1, 12
    @frame.set_size 200, 100
    @message.set_font @small_font
  end
  
  def large
 	  @large_font ||= Font.new "Default", 1, 72
	  @frame.set_size 1200, 700
	  @message.set_font @large_font
  end
  
  def next_page
    @slide_iterator.next if @slide_iterator.next?
		yield if block_given?
    update_message
  end
  
  def prev_page
    if @slide_iterator.prev?
      @slide_iterator.prev
      update_message
    end
  end
  
  def change_color(value)
    value = Color.const_get(value) if value.is_a?(Symbol)
    @message.set_foreground value
  end  
  
  def first_page
    @slide_iterator.first
    update_message
  end
  
  def last_page
    @slide_iterator.last
    update_message
  end
  
  def quit
    @frame.dispose
  end
  
  def update_message
    @message.set_text @slide_iterator.current[:message]
  end
  
  def do_extention
    begin
      eval @slide_iterator.current[:extention] if @slide_iterator.current[:extention]
    rescue SyntaxError => e
      puts "[Syntax Error]Slide ##{@slide_iterator.index}"
      puts e.to_s
      puts @slide_iterator.current[:extention]
    end
  end
end

Presen.new.show
